package org.oschina.api.index.queue;

import org.oschina.Constants;
import org.oschina.api.index.model.IndexHandleBean;
import org.oschina.helper.index.IndexHelper;
import org.oschina.queue.BaseQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 索引处理队列
 */
@Component
public class IndexHandleQueue extends BaseQueue {

	@Autowired
	private IndexHelper indexHelper;
	
	@Scheduled(fixedDelay=1000)
	private synchronized void handle()
	{
		IndexHandleBean bean=(IndexHandleBean)get(Constants.QUEUE_INDEX_HANDLE, IndexHandleBean.class);
		if(bean==null)
			return;
		
		switch(bean.getIndexType())
		{
			case CREATE:
			{
				create(bean.getPath(),bean.getFields(),bean.getValues());
				break;
			}
			case UPDATE:
			{
				update(bean.getPath(),bean.getWhere(),bean.getFields(),bean.getValues());
				break;
			}
			case REMOVE:
			{
				remove(bean.getPath(),bean.getWhere());
				break;
			}
		}
	}
	
	private void create(String path,String fields[],Object values[])
	{
		indexHelper.write(path, fields, values);
	}
	
	private void update(String path,String where,String fields[],Object values[])
	{
		indexHelper.update(path, where,fields, values);
	}
	
	private void remove(String path,String where)
	{
		indexHelper.remove(path, where);
	}
}